// 存储工具 - 替代 chrome.storage.local
// 使用 Electron IPC 与主进程通信

export const storage = {
  // 获取存储值
  async get(keys) {
    if (!window.electronAPI || !window.electronAPI.storage) {
      // 降级到 localStorage
      const result = {}
      const keyArray = Array.isArray(keys) ? keys : Object.keys(keys || {})
      keyArray.forEach(key => {
        const value = localStorage.getItem(key)
        if (value !== null) {
          try {
            result[key] = JSON.parse(value)
          } catch {
            result[key] = value
          }
        }
      })
      return result
    }
    
    return await window.electronAPI.storage.get(keys)
  },

  // 设置存储值
  async set(items) {
    if (!window.electronAPI || !window.electronAPI.storage) {
      // 降级到 localStorage
      Object.keys(items).forEach(key => {
        localStorage.setItem(key, JSON.stringify(items[key]))
      })
      return
    }
    
    return await window.electronAPI.storage.set(items)
  },

  // 删除存储值
  async remove(keys) {
    if (!window.electronAPI || !window.electronAPI.storage) {
      // 降级到 localStorage
      const keyArray = Array.isArray(keys) ? keys : [keys]
      keyArray.forEach(key => {
        localStorage.removeItem(key)
      })
      return
    }
    
    return await window.electronAPI.storage.remove(keys)
  },

  // 监听存储变化
  onChanged(callback) {
    if (!window.electronAPI || !window.electronAPI.storage) {
      // 降级：使用 storage 事件（仅限同源）
      window.addEventListener('storage', (e) => {
        if (e.key && e.newValue !== null) {
          try {
            callback({ [e.key]: { newValue: JSON.parse(e.newValue) } }, 'local')
          } catch {
            callback({ [e.key]: { newValue: e.newValue } }, 'local')
          }
        }
      })
      return
    }
    
    window.electronAPI.storage.onChanged(callback)
  }
}

